<button class="accordion"><strong>Java Code Example</strong></button>
<div class="panel">
    <p><em><strong>Please Note:</strong> There are over 100 more detailed code examples in Java, JavaScript and the REST API below.</em></p>

    <pre class="prettyprint lang-java code"><code class="code">new MockServerClient("localhost", 1080)
    .when(
        request()
            .withMethod("POST")
            .withPath("/login")
            .withBody("{username: 'foo', password: 'bar'}")
    )
    .respond(
        response()
            .withStatusCode(302)
            .withCookie(
                "sessionId", "2By8LOhBmaW5nZXJwcmludCIlMDAzMW"
            )
            .withHeader(
                "Location", "https://www.mock-server.com"
            )
    );</code></pre>
</div>

<button class="accordion"><strong>JavaScript Code Example</strong></button>
<div class="panel">
    <p><em><strong>Please Note:</strong> There are over 100 more detailed code examples in Java, JavaScript and the REST API below.</em></p>

    <pre class="prettyprint lang-java code"><code class="code">var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
    "httpRequest": {
        "method": "POST",
        "path": "/login",
        "body": {
            "username": "foo",
            "password": "bar"
        }
    },
    "httpResponse": {
        "statusCode": 302,
        "headers": {
            "Location": [
                "https://www.mock-server.com"
            ]
        },
        "cookies": {
            "sessionId": "2By8LOhBmaW5nZXJwcmludCIlMDAzMW"
        }
    }
}).then(
    function () {
        console.log("expectation created");
    },
    function (error) {
        console.log(error);
    }
);</code></pre>
</div>

<p>To use the Java client add the <strong>org.mock-server:mockserver-client-java-no-dependencies:{{ site.mockserver_version }}</strong> dependency.

<p>For more details about the different dependency versions see the page on <a href="/where/maven_central.html#mockserver_client_java">Maven Central</a></p>

<p>for example in maven:</p>

<pre><code class="code xml">&lt;<span class="element">dependency</span>&gt;
	&lt;<span class="element">groupId</span>&gt;<span class="element_value">org.mock-server</span>&lt;/<span class="element">groupId</span>&gt;
	&lt;<span class="element">artifactId</span>&gt;<span class="element_value">mockserver-client-java-no-dependencies</span>&lt;/<span class="element">artifactId</span>&gt;
	&lt;<span class="element">version</span>&gt;<span class="element_value">RELEASE</span>&lt;/<span class="element">version</span>&gt;
&lt;/<span class="element">dependency</span>&gt;</code></pre>

<p>A <strong>request matcher expectation</strong> may contain:</p>
<ul>
    <li><strong><a href="#request_matchers">request matcher</a></strong> - used to match which requests this expectation should be applied to</li>
    <li><strong><a href="#actions">action</a></strong> - what action to take, actions include <strong>response</strong>, <strong>forward</strong>, <strong>callback</strong> and <strong>error</strong></li>
    <li><strong><a href="#button_match_request_by_path_exactly_twice">times</a></strong> <em>(optional)</em> - how many times the action should be taken</li>
    <li><strong><a href="#button_match_request_by_path_exactly_once_in_the_next_60_seconds">timeToLive</a></strong> <em>(optional)</em> - how long the expectation should stay active</li>
    <li><strong><a href="#button_match_request_by_priority">priority</a></strong> <em>(optional)</em> - matching is ordered by priority (highest first) then creation (earliest first)</li>
    <li><strong><a href="#button_match_request_update_by_id">id</a></strong> <em>(optional)</em> - used for updating an existing expectation (i.e. when the id matches)</li>
</ul>

<p><strong><a href="/mock_server/using_openapi.html#generate_expectation_from_openapi">open api expectations</a></strong> are also supported using an <a target="_blank" href="https://swagger.io/docs/specification/basic-structure/"><strong>OpenAPI
    v3</strong></a> specifications to generate <strong>request matcher expectations</strong> for each operation, see the section on <strong><a href="/mock_server/using_openapi.html#generate_expectation_from_openapi">open api
    expectations</a></strong> for details.</p>

<a id="matching_order" class="anchor" href="#matching_order">&nbsp;</a>

<h4>Matching Order</h4>

<p>MockServer will match (or play) active expectations in the exact order they are added (if their priority is identical). For example, if an expectation <span class="annotation">A</span> is added with <span class="inline_code">Times.exactly(3)</span>
    then expectation <span class="annotation">B</span> is added with <span class="inline_code">Times.exactly(2)</span> with the same request matcher they will be applied in the following order <span class="annotation">A</span>, <span
            class="annotation">A</span>, <span class="annotation">A</span>, <span class="annotation">B</span>, <span class="annotation">B</span>. Priority can be used to alter the order that expectations are matched; matching is ordered by
    priority (highest first) then creation (earliest first).</p>
<p>Priority can be used to configure a <a href="#button_match_request_by_negative_priority">default expectation or response</a> by specifying a negative value for priority and a very lax request matcher; the lax request matcher ensures the
    default expectation is always matched, but the low priority ensure it is matched last after all other expectations.</p>

<a id="updating_expectations" class="anchor" href="#updating_expectations">&nbsp;</a>

<h4>Updating Expectations</h4>

<p>If an expectation is added and the <strong>id</strong> field matches an existing expectation the existing expectation will be updated (i.e. replaced). A UUID will be used assigned to each expectation if no value for <strong>id</strong>
    is specified.</p>

<p></p>

<a id="request_matchers" class="anchor" href="#request_matchers">&nbsp;</a>

<h3>Request Matchers</h3>

<p>The are two types of <strong>request matcher</strong>:</p>
<ul>
    <li><strong><a href="#request_properties_matchers">request properties matcher</a></strong> - that match requests using HTTP properties such as <strong>method</strong>, <strong>path</strong> or <strong>body</strong></li>
    <li><strong><a href="#request_openapi_matchers">open api request matcher</a></strong> - that match requests using an <a target="_blank" href="https://swagger.io/docs/specification/about/"><strong>OpenAPI</strong></a> definition</li>
</ul>

<a id="request_properties_matchers" class="anchor" href="#request_properties_matchers">&nbsp;</a>

<p>A <strong>request properties matcher</strong> matches requests using one or more of the following properties:</p>

<ul>
    <li><strong>method</strong> - <a href="#request_property_matchers">property matcher</a></li>
    <li><strong>path</strong> - <a href="#request_property_matchers">property matcher</a></li>
    <li><strong>path parameters</strong> - <a href="#request_key_to_multivalue_matchers">key to multiple values matcher</a></li>
    <li><strong>query string parameters</strong> - <a href="#request_key_to_multivalue_matchers">key to multiple values matcher</a></li>
    <li><strong>headers</strong> - <a href="#request_key_to_multivalue_matchers">key to multiple values matcher</a></li>
    <li><strong>cookies</strong> - <a href="#request_key_to_value_matchers">key to single value matcher</a></li>
    <li><strong>body</strong> - <a href="#request_body_matchers">body matchers</a></li>
    <li><strong>secure</strong> - boolean value, true for HTTPS</li>
</ul>

<a id="request_property_matchers" class="anchor" href="#request_property_matchers">&nbsp;</a>

<p>Matching for <strong>properties</strong> can be done using:</p>

<ul>
    <li><strong>string value</strong>
        <ul>
            <li><strong>use for:</strong> method, path, path parameter keys, path parameters values, query parameter keys, query parameters values, header keys, header values, cookie keys, cookie values or bodies</li>
            <li><strong>examples:</strong> <a href="#button_match_request_by_query_parameter_name_regex">method</a>, <a href="#button_match_request_by_path">path</a>, <a href="#button_match_request_by_path_and_path_parameters">path parameters</a>, <a
                    href="#button_match_request_by_cookies_and_query_parameters">query parameters</a>, <a href="#button_match_request_by_headers">headers</a>, <a href="#button_match_request_by_cookies_and_query_parameters">cookies</a></li>
        </ul>
    </li>
    <li><strong>regex value</strong>
        <ul>
            <li><strong>use for:</strong> method, path, path parameter keys, path parameters values, query parameter keys, query parameters values, header keys, header values, cookie keys, cookie values or bodies</li>
            <li><strong>examples:</strong> <a href="#button_match_request_by_method_regex">method</a>, <a href="#button_match_request_by_regex_path">path</a>, <a href="#button_match_request_by_path_parameter_regex_value">path parameters</a>, <a
                    href="#button_match_request_by_query_parameter_name_regex">query parameters</a>, <a href="#button_match_request_by_header_name_regex">headers</a></li>
            <li>for syntax see <a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html">Java regex syntax</a></li>
        </ul>
    </li>
    <li><strong>json schema</strong>
        <ul>
            <li><strong>use for:</strong> method, path, path parameters values, query parameters values, header values, cookie values or bodies</li>
            <li><strong>not supported for:</strong> path parameter keys, query parameter keys, header keys or cookie keys</li>
            <li><strong>examples:</strong> <a href="#button_match_request_by_path_parameter_json_schema_value">path parameters</a>, <a href="#button_match_request_by_query_parameter_value_json_schema">query parameters</a>, <a href="#button_match_request_by_header_value_json_schema">headers</a> , <a href="#button_match_request_by_cookies_value_json_schema">cookies</a></li>
            <li>for syntax see <a target="_blank" href="https://json-schema.org">JSON Schema documentation</a></li>
        </ul>
    </li>
    <li><strong>optional value</strong>
        <ul>
            <li><strong>use for:</strong> method, path, path parameters values, query parameter keys, query parameters values, header keys, header values, cookie keys, cookie values or bodies</li>
            <li><strong>not supported for:</strong> path parameter keys or values, query parameter values, header values or cookie values</li>
            <li><strong>examples:</strong> <a href="#button_match_request_by_optional_query_parameter">query parameters</a>, <a href="#button_match_request_by_optional_header">headers</a>, <a href="#button_match_request_by_optional_cookies">cookies</a></li>
        </ul>
    </li>
    <li><strong>negated value</strong>
        <ul>
            <li><strong>use for:</strong> method, path, path parameter keys, path parameters values, query parameter keys, query parameters values, header keys, header values, cookie keys, cookie values or bodies</li>
            <li><strong>examples:</strong> <a href="#button_match_request_by_not_matching_method">method</a>, <a href="#button_match_request_by_not_matching_path">path</a>, <a href="#button_match_request_by_not_matching_header_value">headers</a>
            </li>
        </ul>
    </li>
</ul>

<a id="request_key_to_multivalue_matchers" class="anchor" href="#request_key_to_multivalue_matchers">&nbsp;</a>

<p>Matching for <strong>key to multiple values</strong> supports multiple values for each key for headers, query parameters and path parameters</p>

<ul>
    <li>Keys support all <a href="#request_property_matchers">property matcher</a> except json schema</li>
    <li>Values support all <a href="#request_property_matchers">property matcher</a> except optional values</li>
    <li>Matching supports two modes:
        <ul>
            <li><strong><a href="#button_match_request_by_query_parameter_by_sub_set">sub set</a></strong> (default) - matches if the request property contains a matching sub set (considering optional keys), therefore there is <strong>at least one matching value</strong> for each
                non-optional key or optional key if present
            </li>
            <li><strong><a href="#button_match_request_by_header_by_matching_key">matching key</a></strong> - matches if the request property contains only matching values (considering optional keys), therefore <strong>all values must match</strong> for each non-optional key or optional
                key if present
            </li>
        </ul>
    </li>
</ul>

<a id="request_key_to_value_matchers" class="anchor" href="#request_key_to_value_matchers">&nbsp;</a>

<p>Matching for <strong>key to single value</strong> supports a single value for each key for cookies</p>

<ul>
    <li>Keys support all <a href="#request_property_matchers">property matcher</a> except json schema</li>
    <li>Values support all <a href="#request_property_matchers">property matcher</a> except optional values</li>
</ul>

<a id="request_body_matchers" class="anchor" href="#request_body_matchers">&nbsp;</a>

<p>Matching for <strong>bodies</strong> can be done using:</p>

<ul>
    <li><strong><a href="#button_match_request_by_body_in_utf16">plain text</a></strong> (i.e. exact match)</li>
    <li><strong><a href="#button_match_request_by_regex_body">regular expression</a></strong> - see <a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html">Java regex syntax</a></li>
    <li><strong><a href="#button_match_request_by_body_with_json_exactly">JSON</a></strong> - supports:
        <ul>
            <li><strong>matchType</strong> to control which fields get matched:
                <ul>
                    <li><strong><a href="#button_match_request_by_body_with_json_exactly">STRICT</a></strong> matches all fields, order of arrays and no additional fields allowed</li>
                    <li><strong><a href="#button_match_request_by_body_with_json_ignoring_extra_fields">ONLY_MATCHING_FIELDS</a></strong> only matches fields provided in the request matcher</li>
                </ul>
            </li>
            <li><strong><a href="#button_match_request_by_body_with_json_placeholders">JSONUnit placeholders</a></strong> to allow fields or values to be ignored or matched by type for example:
                <ul>
                    <li><strong>${json-unit.ignore-element}</strong> ignore a field</li>
                    <li><strong>${json-unit.any-boolean}</strong> match a field as any boolean</li>
                </ul>
                see <a target="_blank"href="https://github.com/lukas-krecan/JsonUnit">JSONUnit documentation</a> for full details
            </li>
        </ul>
    </li>
    <li><strong><a href="#button_match_request_by_body_with_json_schema">JSON Schema</a></strong> - see <a target="_blank" href="https://json-schema.org/">JSON Schema documentation</a></li>
    <li><strong><a href="#button_match_request_by_body_with_json_path">JsonPath</a></strong> - matches if at least one value is returned by the expression, see <a target="_blank"href="https://github.com/json-path/JsonPath">JsonPath documentation</a></li>
    <li><strong><a href="#button_match_request_by_body_with_xml">XML</a></strong> - supports:
        <ul>
            <li><strong><a href="#button_match_request_by_body_with_xml_placeholders">XMLUnit placeholders</a></strong> to allow fields or elements to be ignored or matched by type for example:
                <ul>
                    <li><strong>${xmlunit.ignore}</strong> ignore an element</li>
                    <li><strong>${xmlunit.isNumber}</strong> match an element or attribute as a number</li>
                </ul>
                see <a target="_blank"href="https://github.com/xmlunit/user-guide/wiki/Placeholders">XMLUnit documentation</a> for full details
            </li>
        </ul>
    </li>
    <li><strong><a href="#button_match_request_by_body_with_xml_schema">XML Schema</a></strong> - see <a target="_blank" href="https://www.w3.org/standards/xml/schema.html">XML Schema documentation</a></li>
    <li><strong><a href="#button_match_request_by_body_with_xpath">XPath</a></strong> - matches if at least one value returned by expression, see <a target="_blank" href="https://www.w3.org/TR/2017/REC-xpath-31-20170321/">XPath specification</a></li>
    <li><strong><a href="#button_match_request_by_form_submission_body">form fields</a></strong> (i.e. body parameters)</li>
    <li><strong><a href="#button_match_request_by_binary_body">binary</a></strong></li>
    <li><strong><a href="#button_match_request_by_not_matching_body_with_xpath">negated matcher</a></strong></li>
</ul>

<button id="button_request" class="accordion title"><strong>Request Properties Matcher Code Examples</strong></button>
<div class="panel title">
    {% include_subpage _includes/request_matcher_code_examples.html %}
</div>

<a id="request_openapi_matchers" class="anchor" href="#request_openapi_matchers">&nbsp;</a>

<p>An <strong>open api request matcher</strong> can contain any of the following fields:</p>

<ul>
    <li><strong>specUrlOrPayload</strong> - mandatory value containing an <a target="_blank" href="https://swagger.io/docs/specification/basic-structure/"><strong>OpenAPI v3</strong></a> specifications in either JSON or YAML format as an:
        <ul>
            <li><strong><a href="#button_match_by_openapi_url">HTTP/HTTPS URL</a></strong></li>
            <li><strong><a href="#button_match_by_openapi_filepath">File URL</a></strong></li>
            <li><strong><a href="#button_match_by_openapi_classpath">classpath location</a></strong> (without the classpath: scheme)</li>
            <li><strong><a href="#button_match_by_inline_openapi_json">inline JSON object</a></strong></li>
            <li><strong><a href="#button_match_by_inline_openapi_yaml">inline escaped YAML string</a></strong></li>
        </ul>
    </li>
    <li><strong>operationId</strong> - optional value that specifies which <a href="#button_match_by_openapi_url_and_operation">operation</a> to match against, if <a href="#button_match_by_openapi_url">empty or null</a> all operations are
        matched against
    </li>
</ul>

<p>MockServer creates a set of <strong><a href="#request_properties_matchers">request properties matchers</a></strong> for each <strong>open api request matcher</strong>, to ensures control-plane logic such as <a
        href="/mock_server/clearing_and_resetting.html">clearing expectations</a> or <a href="/mock_server/debugging_issues.html">retrieving expectations</a> work consistently between the two types of request matchers, this can be viewed in
    the <a href="/mock_server/mockserver_ui.html">MockServer UI</a> <a href="/mock_server/mockserver_ui.html#active_expectations">active expectations</a> section.</p>

<button id="button_match_by_openapi" class="accordion title"><strong>OpenAPI Request Matcher Code Examples</strong></button>
<div class="panel title">
    {% include_subpage _includes/openapi_request_matcher_code_examples.html %}
</div>

<a id="actions" class="anchor" href="#actions">&nbsp;</a>

<h3>Actions</h3>

<p>Actions can be one of the following types:</p>
<ul>
    <li><strong><a href="#response_action">response</a></strong> - returns a response defined by using
        <ul>
            <li>a <strong><a href="#button_response_literal_body_only">literal</a></strong></li>
            <li>a <strong><a href="#button_javascript_templated_response">javascript template</a></strong></li>
            <li>a <strong><a href="#button_javascript_velocity_templated_response">velocity template</a></strong></li>
            <li>a <strong><a href="#button_response_class_callback">class callback</a></strong> (must be present in classpath)</li>
            <li>a <strong><a href="#button_response_method_or_closure_callback">method / closure callback</a></strong> (via WebSocket)</li>
        </ul>
    </li>
    <li><strong><a href="#forward_action">forward</a></strong> - forwards modified requests and returns modified response by using
        <ul>
            <li>the <strong><a href="#button_forward_exactly">exact request and response received</a></strong></li>
            <li>an <strong><a href="#button_forward_overridden">static overridden request and / or response</a></strong></li>
            <li>a <strong><a href="#button_forward_overridden_and_modified_req">dynamically modified request and / or response</a></strong></li>
            <li>a <strong><a href="#button_javascript_templated_forward">javascript template (request only)</a></strong></li>
            <li>a <strong><a href="#button_javascript_velocity_templated_forward">velocity template (request only)</a></strong></li>
            <li>a <strong><a href="#button_forward_class_callback">class callback for request and / or response</a></strong> (must be present in classpath)</li>
            <li>a <strong><a href="#button_forward_method_or_closure_callback">method / closure callback for request and / or response</a></strong> (via WebSocket)</li>
        </ul>
    </li>
    <li><strong><a href="#error_action">error</a></strong> - returns an invalid response as a sequence of bytes or closes the connection</li>
</ul>

<p>If no action is present for a request because no <a href="#request_matchers">request matcher</a> was matched then:</p>
<ul>
    <li>if MockServer is being used as a proxy the request is proxied to its destination un-modified</li>
    <li>if the request host header does not match the hostname or IP the request automatically proxied to the host header</li>
</ul>

<a id="response_action" class="anchor" href="#response_action">&nbsp;</a>

<p>A <strong>response action</strong> can be:</p>

<ul>
    <li>
        <p>either a <a href="#button_response_literal_body_only">response literal</a> containing any of the following:</p>
        <ul>
            <li><strong><a href="#button_response_literal_status_code_and_reason_phrase">status code</a></strong></li>
            <li><strong><a href="#button_response_literal_status_code_and_reason_phrase">reason phrase</a></strong></li>
            <li><strong><a href="#button_response_literal_binary_PNG_body">body</a></strong></li>
            <li><strong><a href="#button_response_literal_with_header">headers</a></strong></li>
            <li><strong><a href="#button_response_literal_with_cookie">cookies</a></strong></li>
            <li><strong><a href="#button_response_literal_with_10_second_delay">delay</a></strong></li>
            <li><strong><a href="#button_response_literal_with_connection_options_to_suppress_headers">connectionOptions</a></strong> that can be used to <a href="#button_response_literal_with_connection_options_to_suppress_headers">suppress
                headers</a>, <a href="#button_response_literal_with_connection_options_to_override_headers">override headers</a> or <a href="#button_response_literal_with_connection_options_to_close_socket">close the socket connection</a>
            </li>
        </ul>
    </li>
    <li>
        <p>or a <strong>templated</strong> response using <strong><a href="#button_javascript_templated_response">javascript</a></strong> or <strong><a href="#button_javascript_velocity_templated_response">velocity</a></strong> with a
            <strong><a href="#button_javascript_templated_response_with_delay">delay</a></strong></p>
    </li>
    <li>
        <p>or a <strong>callback</strong> used to dynamically generate a response based on the request:</p>
        <ul>
            <li>
                <p>as a <strong>server side callback</strong> implemented as a <a href="#button_response_class_callback">java class</a> that has a default constructor, implements <span class="annotation">org.mockserver.mock.action.ExpectationResponseCallback</span>
                    and is available on the classpath</p>
            </li>
            <li>
                <p>as a <strong>client side callback</strong> implemented as a <a href="#button_response_method_or_closure_callback">closure</a> using the java or javascript clients</p>
            </li>
        </ul>
    </li>
</ul>

<button id="button_response" class="accordion title"><strong>Response Action Code Examples</strong></button>
<div class="panel title">
    {% include_subpage _includes/response_action_code_examples.html %}
</div>

<a id="forward_action" class="anchor" href="#forward_action">&nbsp;</a>

<p>A <strong>forward action</strong> can be:</p>

<ul>
    <li>
        <p>either an <a href="#button_forward_exactly">exact forwarder</a>, that forwards requests exactly as it receives them, containing the following:</p>
        <ul>
            <li><strong>host</strong></li>
            <li><strong>port</strong></li>
            <li><strong><a href="#button_forward_exactly_in_https">scheme</a></strong></li>
        </ul>
    </li>
    <li>
        <p>or an <a href="#button_forward_overridden">overridden request</a> (or overridden response), with a <strong><a href="#button_forward_overridden_with_delay">delay</a></strong>, that allows any part of a forwarded request or
            response to be replaced or certain fields (path, headers, cookies or query parameters) to be modified</p>
    </li>
    <li>
        <p>or a templated forwarder using <strong><a href="#button_javascript_templated_forward">javascript</a></strong> or <strong><a href="#button_javascript_velocity_templated_forward">velocity</a></strong>, with a <strong><a
                href="#button_javascript_templated_forward_with_delay">delay</a></strong>, that allows requests to be modified or completely re-written before they are forwarded</p>
    </li>
    <li>
        <p>or a <strong>callback</strong> used to dynamically generate the request to forward based on the request received by MockServer:</p>
        <ul>
            <li>
                <p>as a <strong>server side callback</strong> implemented as a <a href="#button_forward_class_callback">java class</a> that has a default constructor, implements <span class="annotation">org.mockserver.mock.action.ExpectationForwardCallback</span>
                    or <span class="annotation">org.mockserver.mock.action.ExpectationForwardAndResponseCallback</span> and is available on the classpath</p>
            </li>
            <li>
                <p>as a <strong>client side callback</strong> implemented as a <a href="#button_forward_method_or_closure_callback">closure</a> using the java or javascript clients</p>
            </li>
        </ul>
    </li>
</ul>

<button id="button_forward" class="accordion title"><strong>Forward Action Code Examples</strong></button>
<div class="panel title">
    {% include_subpage _includes/forward_action_code_examples.html %}
</div>

<a id="error_action" class="anchor" href="#error_action">&nbsp;</a>

<p>An <strong>error action</strong> can return an invalid response as a <a href="#button_random_bytes_error">sequence of bytes</a> or <a href="#button_drop_connection_error">drop the connection</a></p>

<button id="button_error" class="accordion title"><strong>Error Action Code Examples</strong></button>
<div class="panel title">
    {% include_subpage _includes/error_action_code_examples.html %}
</div>
